import { computed, ref } from 'vue'
import type {
  EnergyDataReportList,
  EnergyDataReportProps,
  ReportColumnsItem,
} from '../types'

function useReportState(props: EnergyDataReportProps) {
  const title = computed(() => {
    // 年度
    if (Number(props.quarter) === 5) {
      return `${props.enterpriseName || ''}（${props.year}年）${props.name}`
    }
    if (props.enterpriseName) {
      return `${props.enterpriseName}（${props.year}年第${props.quarter}季度）${props.name}`
    }
    return `${props.name}（${props.year}年第${props.quarter}季度）`
  })

  const fromGovernmentSide = computed(() => {
    return !!(props.isGovernment && props.readonly)
  })

  const flattenColumns = computed(() => {
    const columns = props.columns
    const getItems = (arr: ReportColumnsItem[]) => {
      const result = [];
      (function callback(arr) {
        for (let i = 0; i < arr.length; i++) {
          const v = arr[i]
          if (v) {
            const { children, ...rest } = v
            if (children && children.length > 0) {
              callback(children)
            }
            else if (!rest.hidden) {
              result.push({ ...rest })
            }
          }
        }
      })(arr)
      return result
    }
    return getItems(columns)
  })

  // TODO
  const lists = ref<
    EnergyDataReportList<{
      key: string
      value: string | number
      editable?: boolean
      [propName: string]: any
    }>[]
  >([])

  const informant = computed(() => {
    const listsValue = lists.value
    const item = listsValue[0]?.informant
    if (!item) {
      return {}
    }
    return {
      personInCharge: item.personInCharge || '',
      informer: item.informer || '',
      telephone: item.telephone || '',
      fillInDate: item.fillInDate || '',
    }
  })

  const seriesNo = ref('')
  const inputIndex = ref(-1)
  const rowIndex = ref(-1)
  const showLineNumber = ref(true)
  const visible = ref(false)
  const left = ref(0)
  const top = ref(0)

  return {
    title,
    fromGovernmentSide,
    flattenColumns,
    seriesNo,
    lists,
    informant,
    inputIndex,
    rowIndex,
    showLineNumber,
    visible,
    left,
    top,
  }
}

export default useReportState
